import { FormEvent, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { api } from '../lib/api';
import type { LoginRequest, LoginResponse } from '../types/auth';

const moduleDisplayName = '${moduleDisplayName?js_string}';

const LoginPage = () => {
  const navigate = useNavigate();
  const [form, setForm] = useState<LoginRequest>({ username: '', password: '' });
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    setLoading(true);
    setError(null);
    try {
      await api.post<LoginResponse>('/auth/login', form);
      navigate('/');
    } catch (err) {
      setError(err instanceof Error ? err.message : '登录失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="card" style={{ maxWidth: 420, margin: '0 auto' }}>
      <h2 style={{ marginTop: 0 }}>登录</h2>
      <p style={{ color: '#475569' }}>登录信息将用于访问 {moduleDisplayName} 后台，请接入真实的认证接口。</p>
      <form onSubmit={handleSubmit}>
        <div className="form-field">
          <label htmlFor="username">用户名</label>
          <input
            id="username"
            value={form.username}
            onChange={(event) => setForm((prev) => ({ ...prev, username: event.target.value }))}
            placeholder="输入用户名"
            required
          />
        </div>
        <div className="form-field">
          <label htmlFor="password">密码</label>
          <input
            id="password"
            type="password"
            value={form.password}
            onChange={(event) => setForm((prev) => ({ ...prev, password: event.target.value }))}
            placeholder="输入密码"
            required
          />
        </div>
        {error ? <div style={{ color: '#ef4444' }}>{error}</div> : null}
        <button type="submit" disabled={loading}>
          {loading ? '登录中...' : '登录'}
        </button>
      </form>
    </div>
  );
};

export default LoginPage;

